from django.contrib import auth
from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from sqtp.models import User


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['date_joined','email','id','is_active','is_superuser','phone','realname','username','user_type']


class RegisterSerializer(serializers.ModelSerializer):
    # admin_code不在User字段中
    admin_code = serializers.CharField(default=None)

    class Meta:
        model = User
        fields = ['admin_code', 'username', 'email', 'password', 'phone', 'realname']

    '''
    检验参数是否合法，attrs是返回入参的字典形式
    '''

    def validate(self, attrs):
        if attrs['admin_code'] is not None and attrs['admin_code'] != 'sqtp':
            raise ValidationError('错误的admin_code')
        return attrs  # 放行

    def register(self):
        '''
        self.initial_data：是用户提交的原始数据（通常是 request.data）
        self.validated_data：是 .is_valid() 之后通过校验后的数据
        self.data：
        如果你已经 .is_valid() 并 .save()，那 self.data 是序列化的最终输出结果（通常用于返回给前端）
        如果你还没 .is_valid() 或 .save()，它通常是用 initial_data 包装而成，未校验的数据
        create_user等等会自动将密码那些加密
        '''
        in_params = self.data
        if in_params['admin_code'] is not None:
            in_params.pop('admin_code')
            # 创建管理员用户
            user = User.objects.create_superuser(**in_params)
        else:
            in_params.pop('admin_code')
            # 创建普通用户
            user = User.objects.create_user(**in_params)
        return user


class LoginSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['username', 'password']

    def validate(self, attrs):
        position_parm = ['username', 'password']
        for parm in position_parm:
            if parm not in attrs:
                raise ValidationError("缺少参数")
        user = auth.authenticate(**attrs)
        if not user:
            raise ValidationError("用户名或密码错误")
        return user
